#include <REGX52.H>
#include "nixie.h"
#include "timer0.h"
#include "key.h"
#include "delay.h"
#include "at24c02.h"

unsigned char KeyNum;
unsigned char Min,Sec,MinSec;
unsigned char RunFlag;	
	
void main()
{
	
	Timer0_Init();
	while(1)
	{
		KeyNum=Key();
		if(KeyNum==1)//暂停与启动
		{
			RunFlag=!RunFlag;//启动标志位翻转
		}
		if(KeyNum==2)//清零
		{
			Min=0;
			Sec=0;
			MinSec=0;
		}
		
		if(KeyNum==3)
		{
			AT24C02_WriteByte(0,Min);//将分秒写入AT24C02
			Delay(5);
			AT24C02_WriteByte(1,Sec);
			Delay(5);
			AT24C02_WriteByte(2,MinSec);
			Delay(5);
		}
		
		if(KeyNum==4)
		{
			Min=AT24C02_ReadByte(0);//读出AT24C02数据
			Sec=AT24C02_ReadByte(1);
			MinSec=AT24C02_ReadByte(2);
		}
		
		//数码管每一位显示
		Nixie_SetBuf(1,Min/10);
		Nixie_SetBuf(2,Min%10);
		Nixie_SetBuf(3,11);		//这是横杠
		Nixie_SetBuf(4,Sec/10);
		Nixie_SetBuf(5,Sec%10);
		Nixie_SetBuf(6,11);
		Nixie_SetBuf(7,MinSec/10);
		Nixie_SetBuf(8,MinSec%10);
		
	}
}

/**
  * @brief  秒表驱动函数，在中断中调用
  * @param  无
  * @retval 无
  */
void Sec_Loop()//秒表计数规则
{
	if(RunFlag)
	{
		MinSec++;
		if(MinSec==100)
		{
			MinSec=0;
			Sec++;
			if(Sec>=60)
			{
				Sec=0;
				Min++;
				if(Min>=60)
				{
					Min=0;
				}
			}	
		}
	
	}
}

void Timer0_Routine() interrupt 1	//这里面定义的子函数中不要有Delay函数
{
	static unsigned int T0Count1,T0Count2,T0Count3;

	TL0 = 0x66;				//设置定时初始值
	TH0 = 0xFC;				//设置定时初始值
	T0Count1++;
	if(T0Count1>=20)
	{
		T0Count1=0;
		Key_Loop();//20ms调用一次按键驱动函数
	}
	
	T0Count2++;
	if(T0Count2>=2)
	{
		T0Count2=0;
		Nixie_Loop();//2ms调用一次按键驱动函数
	}
	
	T0Count3++;
	//秒表的最后一位是1/100（即0,01s）秒加1
	if(T0Count3>=10)
	{
		T0Count3=0;
		Sec_Loop();//10ms调用一次按键驱动函数
	}
}
